import React, { useRef, useEffect } from 'react';
import { useTheme, useMediaQuery } from '@mui/material';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, LegendComponent, DataZoomComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import ReactEcharts from 'echarts-for-react';
import { format } from 'date-fns';
import { ChartDataPoint } from '../types/device';

echarts.use([
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  CanvasRenderer,
]);

interface TemperatureHumidityChartProps {
  data: ChartDataPoint[];
}

const TemperatureHumidityChart: React.FC<TemperatureHumidityChartProps> = ({ data }) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const chartRef = useRef<any>(null);

  useEffect(() => {
    // Optional: Dispose chart when component unmounts
    return () => {
      if (chartRef.current) {
        echarts.dispose(chartRef.current.getEchartsInstance());
      }
    };
  }, []);

  const options = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        let tooltipContent = format(new Date(params[0].value[0]), 'yyyy-MM-dd HH:mm:ss') + '<br/>';
        params.forEach((item: any) => {
          const value = item.value[1];
          if (value !== undefined && value !== null) {
            tooltipContent += `${item.seriesName}: ${value.toFixed(1)}${item.seriesName === '温度' ? '°C' : '%'}<br/>`;
          }
        });
        return tooltipContent;
      },
      confine: true,
    },
    legend: {
      data: ['温度', '湿度'],
      bottom: 0,
      textStyle: {
        fontSize: isMobile ? 12 : 14,
        color: theme.palette.text.primary,
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%', // Adjust bottom to make space for legend and dataZoom
      containLabel: true,
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: (value: string) => {
          const date = new Date(value);
          return isMobile
            ? `${date.getHours()}:${date.getMinutes()}`
            : `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
        },
        fontSize: isMobile ? 10 : 12,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '温度 (°C)',
        position: 'left',
        axisLabel: {
          formatter: '{value} °C',
          fontSize: isMobile ? 10 : 12,
        },
        axisLine: {
          lineStyle: {
            color: theme.palette.primary.main,
          },
        },
        axisTick: {
          show: false,
        },
      },
      {
        type: 'value',
        name: '湿度 (%)',
        position: 'right',
        axisLabel: {
          formatter: '{value} %',
          fontSize: isMobile ? 10 : 12,
        },
        axisLine: {
          lineStyle: {
            color: theme.palette.secondary.main,
          },
        },
        axisTick: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        yAxisIndex: 0,
        data: data.map(item => [item.timestamp, item.data.temperature]),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          color: theme.palette.primary.main,
          width: 2,
        },
      },
      {
        name: '湿度',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => [item.timestamp, item.data.humidity]),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          color: theme.palette.secondary.main,
          width: 2,
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside', // 内置于坐标系中
        start: 0,
        end: 100,
        xAxisIndex: [0], // 控制 xAxis
      },
      {
        type: 'slider', // 带有滑动条
        start: 0,
        end: 100,
        xAxisIndex: [0], // 控制 xAxis
        height: isMobile ? 20 : 30,
        bottom: isMobile ? 5 : 10,
        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
        handleSize: '80%',
        handleStyle: {
          color: theme.palette.primary.main,
          shadowBlur: 3,
          shadowColor: 'rgba(0, 0, 0, 0.6)',
          shadowOffsetX: 2,
          shadowOffsetY: 2
        },
      },
    ],
  };

  return (
    <ReactEcharts
      echarts={echarts}
      option={options}
      style={{ height: '100%', width: '100%' }}
      ref={chartRef}
    />
  );
};

export default TemperatureHumidityChart; 